﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Input;
using Common.Interfaces;
using PCSWpfClient.Commands;
using PCSWpfClient.Locator;
using PCSWpfClient.View;
using WpfFeeCalculator.ViewModel;
using Microsoft.Practices.Unity;

namespace PCSWpfClient.ViewModel
{
    class MainWindowViewModel : ItemBaseViewModel
    {
        ObservableCollection<ItemBaseViewModel> _workItems;
        DelegateCommand _priceCommand;

        public MainWindowViewModel()
        {
            RequestClose += MainWindowViewModel_RequestClose;
        }



        void MainWindowViewModel_RequestClose(object sender, EventArgs e)
        {
            View.CloseWindow();
        }

        void ShowPriceView()
        {
            var item = MainWindowModelLocator.Container.Resolve<PriceViewModel>();
            this.WorkItems.Add(item);
            this.SetActiveWorkspace(item);
        }

        void Item_RequestClose(object sender, EventArgs e)
        {
            ItemBaseViewModel item = sender as ItemBaseViewModel;
            item.RequestClose -= Item_RequestClose;
            item.Dispose();
            WorkItems.Remove(item);
        }

        void SetActiveWorkspace(ItemBaseViewModel item)
        {
            Debug.Assert(WorkItems.Contains(item));

            ICollectionView collectionView = CollectionViewSource.GetDefaultView(WorkItems);
            if (collectionView != null)
                collectionView.MoveCurrentTo(item);
        }


        public IMainView View { get; set; }

        public ICommand PriceCommand
        {
            get
            {
                if (_priceCommand == null)
                    _priceCommand = new DelegateCommand(x => ShowPriceView());
                return _priceCommand;
            }
        }

        public ObservableCollection<ItemBaseViewModel> WorkItems
        {
            get
            {
                if (_workItems == null)
                {
                    _workItems = new ObservableCollection<ItemBaseViewModel>();
                }
                return _workItems;
            }
        }

    }
}
